import cssModule from "@/views/system/user/user.module.scss";
import { Dept, Role, User } from "@/types";
import { Tree, Table, Switch, Button, Popconfirm, message } from "antd";
import React, { useEffect, useState } from "react";
import { getDeptTree } from "../../../api/dept/index";
import { DataNode } from "rc-tree/lib/interface";
import { getUserListByPage, getAllRoleList } from "@/api";
import usePageOption from "../../../hooks/usePageOption";
import {
    getUserById,
    addUser,
    updateUser,
    deleteUser,
} from "../../../api/user/index";
import UserFormModal from "./userForm";
import { UserForm } from "../../../types/system/index";
import UserSearch from "./searchForm";

const buildTreeData = (datas: Dept[]): DataNode[] => {
    return datas.map(d => {
        let newD: any = {
            key: d.id,
            title: d.name,
        };
        if (d.children) {
            newD.children = buildTreeData(d.children);
        }
        return newD;
    });
};
const buildUserForm = (user: User): UserForm => {
    return {
        id: user.id,
        phone: user.phone,
        username: user.username,
        nickname: user.nickname,
        deptId: user.dept?.id,
        roles: user.roles?.map(r => r.id),
    } as UserForm;
};
const UserPage: React.FC = () => {
    const columns = [
        {
            title: "用户名",
            dataIndex: "username",
            key: "username",
            width: "100px",
        },
        {
            title: "用户名称",
            dataIndex: "nickname",
            key: "nickname",
            width: "150px",
        },
        {
            title: "手机",
            dataIndex: "phone",
            key: "phone",
            width: "150px",
        },
        {
            title: "用户状态",
            dataIndex: "dataStatus",
            key: "dataStatus",
            width: "100px",
            render(dataStatus: number, row: User) {
                return (
                    <Switch
                        checkedChildren="启用"
                        defaultChecked={dataStatus === 1}
                        unCheckedChildren="禁用"
                        onChange={v => {
                            changeStatus(row.id, v);
                        }}
                    />
                );
            },
        },
        {
            title: "创建时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "更新时间",
            dataIndex: "updateTime",
            key: "updateTime",
        },
        {
            title: "操作",
            key: "handle",
            width: "200px",
            render(row: User) {
                return (
                    <>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                editRowHandler(row);
                            }}
                        >
                            编辑
                        </Button>
                        <Popconfirm
                            title="是否要删除当前角色"
                            onConfirm={() => {
                                deleteUserById(row.id);
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="link" size="small">
                                删除
                            </Button>
                        </Popconfirm>
                    </>
                );
            },
        },
    ];
    const [deptId, setDeptId] = useState<any>(null);
    const onSelect = (selectKey: any[]) => {
        setDeptId(selectKey[0]);
    };
    const [loading, setLoading] = useState(false);
    const [userList, setUserList] = useState<User[]>([]);
    const [pageConfig, setPageConfig] = useState({ page: 1, pageSize: 10 });
    const [searchForm, setSearchForm] = useState({});
    const [pageOption, setPageOption] = usePageOption((page, pageSize) => {
        setPageConfig({
            page,
            pageSize: pageSize ? pageSize : pageConfig.pageSize,
        });
        pageSize && setPageOption({ ...pageOption, pageSize });
    });
    const getUserList = () => {
        setLoading(true);
        getUserListByPage({ ...searchForm, deptId, ...pageConfig }).then(
            res => {
                setLoading(false);
                setUserList(res.data.list);
                setPageOption({ ...pageOption, total: res.data.total });
            }
        );
    };
    const [deptTree, setDeptTree] = useState<DataNode[]>([]);
    const [rawDeptTree, setRawDeptTree] = useState<Dept[]>([]);
    const [visible, setVisible] = useState(false);
    const [roleList, setRoleList] = useState<Role[]>([]);
    const [editForm, setEditForm] = useState<UserForm | null>(null);
    const editRowHandler = (row: User) => {
        getUserById(row.id).then(res => {
            const user = res.data;
            setEditForm(buildUserForm(user));
            setVisible(true);
        });
    };
    let submitFlag = false;
    const submit = async (form: UserForm) => {
        if (submitFlag) {
            return;
        }
        submitFlag = true;
        try {
            if (!editForm) {
                await addUser(form);
            } else {
                await updateUser(form);
            }
            setVisible(false);
            getUserList();
        } catch {
            console.log("添加修改失败");
        }
        submitFlag = false;
    };
    const deleteUserById = (id: number) => {
        deleteUser(id).then(() => {
            message.success("删除成功");
            getUserList();
        });
    };
    const changeStatus = (id: number, v: boolean) => {
        getUserById(id).then(res => {
            const userForm: any = buildUserForm(res.data);
            userForm.dataStatus = v ? 1 : 0;
            updateUser(userForm).then(() => {
                message.success("更新成功");
                getUserList();
            });
        });
    };
    const onSearch = (v: any) => {
        setSearchForm(v);
        setPageConfig({ ...pageConfig, page: 1 });
    };
    useEffect(() => {
        getUserList();
    }, [pageConfig]);
    useEffect(() => {
        getUserList();
    }, [deptId]);
    useEffect(() => {
        getDeptTree({ dataStatus: 1 } as any).then(res => {
            setRawDeptTree(res.data);
            setDeptTree(buildTreeData(res.data));
        });
        getAllRoleList().then(res => {
            setRoleList(res.data);
        });
    }, []);
    return (
        <div className={cssModule.userContainer}>
            <div className={cssModule.deptWrap}>
                <Tree
                    key={deptTree.length}
                    blockNode
                    showLine
                    showIcon
                    defaultExpandAll
                    treeData={deptTree}
                    onSelect={onSelect}
                ></Tree>
            </div>
            <div className={cssModule.userWrap}>
                <UserSearch
                    onSearch={onSearch}
                    roleList={roleList}
                    onRest={() => {
                        setSearchForm({});
                        setPageConfig({ ...pageConfig, page: 1 });
                    }}
                ></UserSearch>
                <div className={cssModule.btnWrap}>
                    <Button type="default" onClick={() => setVisible(true)}>
                        新建
                    </Button>
                </div>
                <Table
                    bordered
                    loading={loading}
                    columns={columns}
                    rowKey="id"
                    dataSource={userList}
                    pagination={pageOption}
                ></Table>
            </div>
            <UserFormModal
                deptId={deptId}
                deptTree={rawDeptTree}
                visible={visible}
                roleList={roleList}
                onCancel={() => {
                    setEditForm(null);
                    setVisible(false);
                }}
                editForm={editForm}
                submit={submit}
            ></UserFormModal>
        </div>
    );
};
export default UserPage;
